Plotly

Intro to Plotly in R

Jingqi Huang, [NAME 2]

Overview

Basic grammar for plotly is simple. We can then create interactive plots of different type by changing the number of variable and graph type. If type and more are not specified, by default will set to what makes most sense.

p <- plot_ly(dataframe, x=~column, y=~column2, type="graph type such as scatter, bar, box, heatmap, etc.", mode="mode type such as markers, lines, and etc.")
p <-p %>% add_trace()
p <-p %>% add_notations()
p <-p %>% layout()
p

Multiple parts on the same graph can be added with add_trace() and add changed configurations.

Multiple texts and be set by add_notations() on whatever locations by xref and yref.

Axis and title can be set by layout().

Plotly can convert ggplot graph to interactive mode by wrap ggplot p with ggplotly(p).

Install and Packages

# install.packages("ggplot2")
# install.packages("plotly")
library(ggplot2)
library(plotly)
library(dplyr)

Basic examples

Histogram

df <- data.frame(type =rep(c("A", "B"), each=500), subtype=rep(c("1", "2"), each=250), value = rnorm(1000))
p <- ggplot(df, aes(x=value, fill=subtype))+
  geom_histogram(position="identity", alpha=0.5, binwidth=0.2)+
  facet_grid(~type)
ggplotly(p)

2D Histogram

p <- plot_ly(x = filter(df, type=="A")$value, y = filter(df, type=="B")$value)
p2<-subplot(p %>% add_markers(alpha=0.4), p%>%add_trace(type='histogram2dcontour'), p%>%add_histogram2d())
p2

Boxplot

plot_ly(diamonds, x = ~price/carat, y = ~clarity, color = ~clarity, type = "box") %>%
  layout(title="Interactive BoxPlot with Plotly")
# Or 
p <- ggplot(diamonds, aes(x=clarity, y=price/carat, color=clarity)) +
  geom_boxplot() + 
  coord_flip() +
  ggtitle("BoxPlot with ggplot2")
# ggplotly(p), also generate interactive graph

2D Scatter Plot

plot_ly(filter(diamonds, color=='D'), x = ~carat, y = ~price, color = ~clarity, 
        marker = list(size=4, opacity=0.5), 
        # hover text
        text = ~paste("Price: ", price, "$<br>Cut: ", cut, "<br>Clarity: ", clarity)) %>%
  # set title and axis
  layout(title="Interactive Scatter Plot with Plotly")

3D Scatter Plot

plot_ly(diamonds[sample(nrow(diamonds), 1000), ], x=~price/carat, y=~table, z=~depth, color=~cut, 
        marker = list(size=4, opacity=0.5))%>%
  layout(title="Interactive 3D Scatter Plot with Plotly")
mtcars <- mutate(mtcars, type = case_when(mtcars$am == 0 ~ "Auto", mtcars$am == 1 ~ "Manual"))
plot_ly(mtcars, x=~mpg, y=~wt, z=~hp, color=~type) %>%
  layout(title="Interactive 3D Scatter Plot with Plotly", scene = list(xaxis = list(title = "mpg"), yaxis = list(title = "weight"), zaxis = list(title = "horsepower")))

Line Plot

a <- rnorm(100, 5, 1)
b <- rnorm(100, 0, 1)
c <- rnorm(100, -5, 1)
df <- data.frame(x=c(1:100), a, b, c)

plot_ly(df, x = ~x) %>%
  add_trace(y = ~a, name="line", type="scatter", mode = "lines", line=list(color='rgb(23, 54, 211)', width=2)) %>% 
  add_trace(y=~b, name="dot line with markers", mode = "lines+markers", line=list(dash='dot')) %>% 
  add_trace(y=~c, name="scatter markers only", mode = "markers") %>%   #same as scatter plot
  layout(title="Interactive Line Plot with Plotly", yaxis=list(title="value"))

Bar Plot

# plot_ly(diamonds, x=~cut, color=~clarity, type="histogram")
plot_ly(count(diamonds, cut, clarity), x=~cut, y=~n, color=~clarity, type="bar", text=~n, marker=list(opacity=0.4, line=list(color='rgba(8,48,148, 1)', width=1.5))) %>% 
  layout(barmode = 'group')

Animations with Plotly

df <- data.frame(x = c(1:10), y = rnorm(10), time = c(1:10))
plot_ly(df, x = ~x, y = ~y, frame = ~time, type = 'scatter', mode = 'markers', showlegend = F)
library(gapminder)
df <- gapminder 
plot_ly(df, x=~gdpPercap, y=~lifeExp, color=~continent, size=~pop, frame=~year, type="scatter", mode="markers", text=~country, hoverinfo = "text") %>%layout(xaxis = list(type = "log"))